package cn.tedu.boot.demo.controller.handler;

import cn.tedu.boot.demo.ex.*;
import cn.tedu.boot.demo.web.JsonResult;
import cn.tedu.boot.demo.web.State;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
        if (e instanceof UsernameDuplicateException) {
            return JsonResult.fail(State.ERR_USERNAME, e.getMessage());
        } else if (e instanceof UserNotFoundException) {
            return JsonResult.fail(State.ERR_USERNAME, e.getMessage());
        } else if (e instanceof UserStateException) {
            return JsonResult.fail(State.ERR_STATE, e.getMessage());
        } else if (e instanceof PasswordNotMatchException) {
            return JsonResult.fail(State.ERR_PASSWORD, e.getMessage());
        } else {
            return JsonResult.fail(State.ERR_INSERT, e.getMessage());
        }
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
        return JsonResult.fail(State.ERR_BAD_REQUEST, defaultMessage);
    }

}
